package com.tree.leetcode.tree;

import com.tree.leetcode.common.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @ClassName com.tree.leetcode.tree
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 3/2/24 7:48 PM
 * @Version 1.0
 */
public class InOrderTraversal_94 {

    public static void main(String[] args) {

    }

    public List<Integer> inorderTraversal(TreeNode root) {
        List res = new ArrayList();
        inorder(root, res);
        return  res;

    }

    public static void inorder(TreeNode root,List list) {
        if (root == null) {return ;}
        inorder(root.left, list);
        list.add(root.val);
        inorder(root.right, list);
    }

    /**
     * 迭代方法
     * @param root
     * @param list
     * @return
     */
    public void inorderTraversalWithIterator(TreeNode root, List list) {
        Stack<TreeNode> stack = new Stack();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()){
            //一直向左
            if(cur != null){
                stack.push(cur);
                cur = cur.left;
            }else {
                //取上一个节点
                cur = stack.pop();
                list.add(cur.val);
                cur = cur.right;
            }
        }

    }
}
